import React, { PureComponent } from 'react';
// 引入样式
import './scss/translate.scss'
// 发送axios
import Axios from 'axios';
// 引入样式
import { message, Input } from 'antd';
// 引入点击复制到粘贴板的办法
import copy from 'copy-to-clipboard';
let { TextArea } = Input
export default class Translate extends PureComponent {
  constructor() {
    super()
    this.state = {
      textArea: '',
      istextArea: '',
      //音频链接
      translateAudio: '',
      // 历史记录数组
      historyList: []
    }
  }
  // input输入时的回调函数
  handleInput = ({ target }) => {
    let { name, value } = target
    // 设置input和state同步
    this.setState({
      [name]: value
    })
  }
  // 翻译
  gettranslate = () => {
    let { textArea, historyList } = this.state;
    if (!textArea) {
      message.info({ content: '必须有内容', className: 'bulletChatMessage' });
      return;
    }
    // 翻译
    Axios.create({
      baseURL: `https://api88.net/api/fanyi/?text=${textArea}&from=auto&to=auto`
    }).get().then(err => {
      let translation = err.data.trans_result[0].dst;
      // 创建一个对象存储历史数据
      let historyObj = {
        translate: textArea,
        translation
      };
      let list = JSON.parse(JSON.stringify(historyList));
      list.unshift(historyObj);
      this.setState({
        istextArea: translation,
        // 存入历史记录
        historyList: list
      })
    }).catch(() => {
      message.error({ content: '您查询的内容暂时没有译文', className: 'bulletChatMessage' });
    })
  }
  // 首页文字点击
  BtnCopy = () => {
    if (this.state.istextArea) {
      if (copy(this.state.istextArea)) {
        message.success({ content: '译文复制成功', className: 'bulletChatMessage' });
      } else {
        message.error({ content: '您的设备不支持自动复制', className: 'bulletChatMessage' });
      }
    }
  }
  // 清空多行文本框
  deleteTextArea = () => {
    this.setState({
      textArea: '',
      istextArea: ''
    })
  }
  // 文本语音播放
  voiceText = () => {
    let { textArea } = this.state;
    if (!textArea) {
      return;
    }
    // 语音转
    let audio = document.getElementById('translateAudioId');
    this.setState({
      translateAudio: `https://api88.net/api/tts/?text=${textArea}&per=0&spd=5&pit=5&vol=9`
    }, () => {
      audio.play().catch(() => {
        message.info({ content: '网络较差，暂无法播放', className: 'bulletChatMessage' })
      })
    })
  }
  // 译文语音播放
  voicebody = () => {
    let { istextArea } = this.state;
    if (!istextArea) {
      return;
    }
    // 语音转
    let audio = document.getElementById('translateAudioId');
    this.setState({
      translateAudio: `https://api88.net/api/tts/?text=${istextArea}&per=0&spd=5&pit=5&vol=9`
    }, () => {
      audio.play().catch(() => {
        message.info({ content: '网络较差，暂无法播放', className: 'bulletChatMessage' })
      })
    })
  }
  // 历史记录
  setIsHistoryList = (obj) => {
    this.setState({
      textArea: obj.translate,
      istextArea: obj.translation
    })
  }
  render () {
    let { istextArea, textArea, translateAudio, historyList } = this.state;
    return (
      <div className='translate'>
        <h3>翻译</h3>
        <div className='translate_top'>
          <TextArea rows={4} placeholder='请输入文字' value={textArea} name='textArea' onChange={this.handleInput} maxLength='200' className='translate_TextArea' />
          {/* 清空 */}
          <img src={require('./image/deleteinput.png')} alt="清空" className='translate_delete' onClick={this.deleteTextArea} />
          {/* 语音 */}
          <img src={require('./image/yuyin.png')} alt="语音" className='translate_yuyin' onClick={this.voiceText} />
        </div>
        {/* 翻译 */}
        <img src={require('../image/fanyi.png')} alt="翻译" className='translate_fanyi' onClick={this.gettranslate} />
        <div className='translate_body'>
          <TextArea rows={4} placeholder='译文' value={istextArea} name='istextArea' onChange={this.handleInput} maxLength='100' className='translate_TextArea' />
          {/* 语音 */}
          <img src={require('./image/yuyin.png')} alt="语音" className='translate_yuyin' onClick={this.voicebody} />
          {/* 复制 */}
          <img src={require('./image/copy.png')} alt="复制" className='translate_delete' onClick={this.BtnCopy} />
        </div>
        {/* 语音播放 */}
        <audio src={translateAudio} controls="controls" style={{ display: 'none' }} id='translateAudioId'>
        </audio>
        {/* 历史记录 */}
        {
          historyList.length !== 0 ?
            <div className='setIsHistory'>
              <div className='setIsHistory_top'>
                <img src={require('./image/history.png')} alt="历史记录" />
                <span>历史记录</span>
              </div>
              {/* 历史记录内容 */}
              <ul className='setIsHistory_body'>
                {
                  historyList.map((list, index) => {
                    return (
                      <li className='setIsHistory_body_list' onClick={() => this.setIsHistoryList(list)} key={index}>{list.translate}</li>
                    )
                  })
                }
              </ul>
            </div>
            : ''
        }
      </div>
    )
  }
}